/*
 * Copyright (c) Thorben Linneweber and others
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

using System;
using Jitter2.DataStructures;
using Jitter2.Dynamics;
using Jitter2.LinearMath;

using SoftFloat;

namespace Jitter2.Collision.Shapes
{
	
	public interface IUpdatableBoundingBox
	{
	    public void UpdateWorldBoundingBox(sfloat dt);
	}
	
	/// <summary>
	/// Represents an object that can be intersected by a ray.
	/// </summary>
	public interface IRayCastable
	{
	    /// <summary>
	    /// Performs a ray cast against the object, checking if a ray originating from a specified point
	    /// and traveling in a specified direction intersects with the object.
	    /// </summary>
	    /// <param name="origin">The starting point of the ray.</param>
	    /// <param name="direction">
	    /// The direction of the ray. This vector does not need to be normalized.
	    /// </param>
	    /// <param name="normal">
	    /// When this method returns, contains the surface normal at the point of intersection, if an intersection occurs.
	    /// </param>
	    /// <param name="lambda">
	    /// When this method returns, contains the scalar value representing the distance along the ray's direction vector
	    /// from the <paramref name="origin"/> to the intersection point. The hit point can be calculated as:
	    /// <c>origin + lambda * direction</c>.
	    /// </param>
	    /// <returns>
	    /// <c>true</c> if the ray intersects with the object; otherwise, <c>false</c>.
	    /// </returns>
	    public bool RayCast(in NVector3 origin, in NVector3 direction, out NVector3 normal, out sfloat lambda);
	}
	
	/// <summary>
	/// The main entity of the collision system. Implements <see cref="ISupportMappable"/> for
	/// narrow-phase and <see cref="IDynamicTreeProxy"/> for broad-phase collision detection.
	/// The shape itself does not have a position or orientation. Shapes can be associated with
	/// instances of <see cref="RigidBody"/>.
	/// </summary>
	public abstract class Shape : IDynamicTreeProxy, IUpdatableBoundingBox, ISupportMappable, IRayCastable
	{
	    protected NVector3 centerOffset;
        /// <summary>
        /// Gets or sets the center offset of the capsule.
        /// </summary>
        public NVector3 CenterOffset
        {
            get => centerOffset;
            set
    
            {
                {
                    if (centerOffset == value)
                        return;
                    centerOffset = value;
                    UpdateWorldBoundingBox(0.0f);
                }
            }
        }
    

	    int IListIndex.ListIndex { get; set; } = -1;
	
	    /// <summary>
	    /// A 64-bit integer representing the shape ID. This is used by algorithms that require
	    /// arranging shapes in a well-defined order.
	    /// </summary>
	    public readonly ulong ShapeId = World.RequestId();
	
	    /// <summary>
	    /// The bounding box of the shape in world space. It is automatically updated when the position or
	    /// orientation of the corresponding instance of <see cref="RigidBody"/> changes.
	    /// </summary>
	    public JBBox WorldBoundingBox { get; protected set; }
	
	    int IDynamicTreeProxy.NodePtr { get; set; }
	
	    protected void SweptExpandBoundingBox(sfloat dt)
	    {
	        NVector3 sweptDirection = dt * Velocity;
	
	        JBBox box = WorldBoundingBox;
	
	        sfloat sxa = libm.Abs(sweptDirection.X);
	        sfloat sya = libm.Abs(sweptDirection.Y);
	        sfloat sza = libm.Abs(sweptDirection.Z);
	
	        sfloat max = libm.Max(libm.Max(sxa, sya), sza);
	
	        if (sweptDirection.X < (sfloat)0.0f) box.Min.X -= max;
	        else box.Max.X += max;
	
	        if (sweptDirection.Y < (sfloat)0.0f) box.Min.Y -= max;
	        else box.Max.Y += max;
	
	        if (sweptDirection.Z < (sfloat)0.0f) box.Min.Z -= max;
	        else box.Max.Z += max;
	
	        WorldBoundingBox = box;
	    }
	
	    public bool IsRegistered => (this as IListIndex).ListIndex != -1;
	
	    [ReferenceFrame(ReferenceFrame.World)]
	    public abstract NVector3 Velocity { get; }
	
	    [ReferenceFrame(ReferenceFrame.World)]
	    public abstract void UpdateWorldBoundingBox(sfloat dt /*= (sfloat)0.0f*/);
	
	    [ReferenceFrame(ReferenceFrame.World)]
	    public abstract bool RayCast(in NVector3 origin, in NVector3 direction, out NVector3 normal, out sfloat lambda);
	
	    /// <inheritdoc/>
	    [ReferenceFrame(ReferenceFrame.Local)]
	    public abstract void SupportMap(in NVector3 direction, out NVector3 result);
	
	    /// <inheritdoc/>
	    [ReferenceFrame(ReferenceFrame.Local)]
	    public abstract void GetCenter(out NVector3 point);
	}
}
